<template>
  <main class="container">
    <div class="hearder">
      <div class="h_left">
        <div class="h_top">
          <card class="selfHome" height="auto">
            <el-avatar :size="80" :src="userStore.user.avatar"></el-avatar>
            <p class="nameText">{{ userStore.user.nickName }}</p>
            <span class="dirText">{{ `${sex} | ${userStore.user.dept?.deptName}${userStore.roles[0]}` }}</span>
          </card>
          <card title="代办通知" height="auto">
            <card title="审批任务" class="noticeT">
              <div class="noticeLeft">
                <div class="noticeL">
                  <p class="noticeFlexNum">{{ waitLength }}</p>
                  <span class="noticeWait" @click="awitApproval">待审批</span>
                </div>
                <el-divider direction="vertical"></el-divider>
                <div class="noticeL">
                  <p class="noticeFlexNum">{{ doneLength }}</p>
                  <span class="noticeWait" @click="$router.push('/processManagement/historyProcess')">已审批</span>
                </div>
              </div>
            </card>
          </card>
        </div>
        <div class="h_bottom">
          <card title="账单异常">
            <div class="warnNotice">
              <div v-for="bill in billException" :key="bill.msgType" class="warnNoticeBox">
                <p class="warnNoticeNum">{{ bill.number }}</p>
                <span class="warnNoticeWait" @click="onException(bill)">
                  {{ bill.msgName }}
                </span>
              </div>
            </div>
          </card>
          <card title="预警通知" style="margin-left: 10px;">
            <div class="warnNotice">
              <div v-for="warn in warningNotice" :key="warn.msgType" class="warnNoticeBox">
                <p class="warnNoticeNum">{{ warn.number }}</p>
                <span class="warnNoticeWait" @click="onOrder(warn)">{{ warn.msgName }}</span>
              </div>
            </div>
          </card>
        </div>
      </div>
      <div class="h_right">
        <!-- 快捷应用 -->
        <fast-app />
      </div>
    </div>
    <footer>
      <!-- 工作通知 -->
      <work-notice ref="workNoticeRef" />
    </footer>
  </main>
</template>
<script setup lang='ts'>
import { computed, ref,reactive, onActivated, watch, h, onMounted, onUnmounted } from 'vue'
import { ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
import card from './card.vue'
import FastApp from './FastApp.vue'
import WorkNotice from './WorkNotice.vue'
import useUserStore from '@/store/modules/user'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import useWsStore from '@/store/modules/websocket'
import { queryTaskByInstanceId } from '@/api/home'

const userStore = useUserStore()
const router = useRouter()
const wsStore = useWsStore()
const dicts = useDicts()
dicts.setDicts(DictDirection.用户性别)
// 性别
const sex = computed(() => {
  const obj = dicts[DictDirection.用户性别].find(i => i.dictValue == userStore.user.sex)
  return obj && obj.dictLabel
})

const workNoticeRef = ref()
const waitLength = ref<number>(0)
const doneLength = ref<number>(0)
const todoData = ref<any[]>([])
const billException = reactive([
  { number: 0, msgName: '超账期未结算', msgType: null },
  { number: 0, msgName: '已出单未推送(2天)', msgType: null },
  { number: 0, msgName: '已回款未核销(2天)', msgType: null },
])
const warningNotice = reactive([
  { number: 0, msgName: '订单异常', msgType: null },
  { number: 0, msgName: '仓库异常', msgType: null },
])

const defaultIndex = ref<number>(0)
const flag = ref<boolean>(false)

onActivated(() => {
  open(defaultIndex.value, flag.value, 0)
})

// 待审批
const awitApproval = () => {
  router.push({
    path: '/processManagement/task',
    query: { id: todoData.value.msgId },
  })
}

// 账单异常
const onException = (abnormal, isBounced?) => {
  const { msgName, msgType, number } = abnormal
  router.push({
    path: '/orderException',
    query: { msgName, msgType, number, isBounced },
  })
}
// 预警通知
const onOrder = (warn, isBounced?) => {
  const { msgName, msgType, number } = warn
  router.push({
    path: '/Order',
    query: { msgName, msgType, number, isBounced },
  })
}

// 显示最新未读任务
const open = (arrIndex:number, flagBol: boolean, offsetNum?: number) => {
  const offsetAmount = 0 + offsetNum
  const index = arrIndex
  if (todoData.value.length && index < todoData.value.length && flagBol === false) {
    flag.value = true
    const notifyClose = ElNotification({
      title: `${ todoData.value[index].msgName }`,
      message: h('i', { style: 'color: teal; cursor: pointer;' }, [h('i', null, `有一条新${ todoData.value[index].msgName }`), h('div', { style: 'cursor: pointer;' }, '查看详情')]),
      position: 'bottom-right',
      duration: 30000,
      offset: offsetAmount,
      onClick: () => {
        const { msgType, msgId } = todoData.value[index]
        // 工作最新消息  待审批最新消息
        if (msgType === wsStore.MSG_TYPE_MAP.WORK_NOTICE 
                || msgType === wsStore.MSG_TYPE_MAP.TODO_NOTICE) {
          queryTaskByInstanceId({ instanceId: msgId }).then(res => {
            msgType === wsStore.MSG_TYPE_MAP.WORK_NOTICE ? workNoticeRef.value.cellClick(msgId, true) : awitApproval()
          })
        } else if (msgType === wsStore.MSG_TYPE_MAP.BILL_NOT_PUSH_NOTICE 
                || msgType === wsStore.MSG_TYPE_MAP.UNVERIFICATION_NOTICE 
                || msgType === wsStore.MSG_TYPE_MAP.MORE_PAYMENT_NOTICE) {
          // 账单异常
          onException(todoData.value[index], true)
        } else if (msgType === wsStore.MSG_TYPE_MAP.ORDER_ABNORMAL_NOTICE) {
          // 订单异常
          onOrder(todoData.value[index], true)
        }
        flag.value = false
        todoData.value.splice(index, 1)
        notifyClose.close()
        open(0, flag.value)
      },
      onClose: () => {
        flag.value = false
        open(++defaultIndex.value, flag.value, -120)
      },
    })
  }
}

watch([todoData], () => {
  open(defaultIndex.value, flag.value, 0)
}, {
  immediate: true,
  deep: true,
})

// 待审批
wsStore.onMessage({ sign: wsStore.SIGN_MAP.TODO_NOTICE_PUSH }, (data) => {
  // console.log(data, '待审批')
  waitLength.value = data.data
})
// 已审批
wsStore.onMessage({ sign: wsStore.SIGN_MAP.APPROVAL_NOTICE_PUSH }, (data) => {
  // console.log(data, '已审批')
  doneLength.value = data.data
})
  
// 订单异常
wsStore.onMessage({ sign: wsStore.SIGN_MAP.ORDER_ABNORMAL_NOTICE_PUSH }, (data) => {
  // console.log(data, '订单异常')
  warningNotice[0].number = data.data
  warningNotice[0].msgType = data.exceptionType
})
// 账单超账期异常
wsStore.onMessage({ sign: wsStore.SIGN_MAP.MORE_PAYMENT_NOTICE_PUSH }, (data) => {
  // console.log(data, '账单超账期异常')
  billException[0].number = data.data
  billException[0].msgType = data.exceptionType
})
// 账单已出单未推送（2天）
wsStore.onMessage({ sign: wsStore.SIGN_MAP.BILL_NOT_PUSH }, (data) => {
  // console.log(data, '账单已出单未推送（2天）')
  billException[1].number = data.data
  billException[1].msgType = data.exceptionType
})
// 账单已回款未核销（2天）
wsStore.onMessage({ sign: wsStore.SIGN_MAP.UNVERIFICATION_BILL_PUSH }, (data) => {
  // console.log(data, '账单已回款未核销（2天）')
  billException[2].number = data.data
  billException[2].msgType = data.exceptionType
})
// 仓库分配异常通知
wsStore.onMessage({ sign: wsStore.SIGN_MAP.WAREHOUSE_ALLOT_NOTICE_PUSH }, (data) => {
  // console.log(data, '仓库分配异常通知')
  warningNotice[1].number = data.data
  warningNotice[1].msgType = data.exceptionType
})

// -------------最新消息
const pushNewMsg = (data) => {
  todoData.value.push(data)
}
// 待审批最新消息
wsStore.onMessage({ msgType: wsStore.MSG_TYPE_MAP.TODO_NOTICE }, pushNewMsg)
// 工作最新消息
wsStore.onMessage({ msgType: wsStore.MSG_TYPE_MAP.WORK_NOTICE }, pushNewMsg)
// 超账期未结算最新消息
wsStore.onMessage({ msgType: wsStore.MSG_TYPE_MAP.MORE_PAYMENT_NOTICE }, pushNewMsg)
// 已出单未推送(2天)最新消息
wsStore.onMessage({ msgType: wsStore.MSG_TYPE_MAP.BILL_NOT_PUSH_NOTICE }, pushNewMsg)
// 账单已回款未核销（2天)最新消息
wsStore.onMessage({ msgType: wsStore.MSG_TYPE_MAP.UNVERIFICATION_NOTICE }, pushNewMsg)
// 订单异常最新消息
wsStore.onMessage({ msgType: wsStore.MSG_TYPE_MAP.ORDER_ABNORMAL_NOTICE }, pushNewMsg)

const getData = () => {
  // 待审批
  wsStore.send(wsStore.SIGN_MAP.TODO_NOTICE_PUSH)
  // // 已审批
  wsStore.send(wsStore.SIGN_MAP.APPROVAL_NOTICE_PUSH)
  // // 订单异常 
  wsStore.send(wsStore.SIGN_MAP.ORDER_ABNORMAL_NOTICE_PUSH)
  // // 账单超账期异常
  wsStore.send(wsStore.SIGN_MAP.MORE_PAYMENT_NOTICE_PUSH)
  // 账单已出单未推送（2天）
  wsStore.send(wsStore.SIGN_MAP.BILL_NOT_PUSH)
  // 账单已回款未核销（2天）
  wsStore.send(wsStore.SIGN_MAP.UNVERIFICATION_BILL_PUSH)
  // // 仓库分配异常通知
  wsStore.send(wsStore.SIGN_MAP.WAREHOUSE_ALLOT_NOTICE_PUSH)
}
getData()
</script>
<style lang="less" scoped>
.container {
  // background-color: rgb(240,247,255);
  padding: 10px;
  .hearder {
    display: flex;
    .h_left {
      width: 60%;
      .h_top {
        display: flex;
        align-items: stretch;
        .selfHome {
          text-align: center;
          margin-right: 10px;
          background-image: linear-gradient(to bottom, rgb(200 229 250), #fff);
          .nameText {
            font-size: 20px;
            font-weight: 700;
          }
          .dirText {
            font-size: 14px;
          }
        }
        .noticeT {
          margin-top: 30px;
          background-image: linear-gradient(to top, rgb(240 248 255), #fff);
        }
        .noticeLeft {
          display: flex;
          justify-content: space-around;
          ::v-deep .el-divider--vertical {
            height: 4em;
          }
          .noticeL {
            text-align: center;
            .noticeFlexNum {
              font-size: 25px;
              margin: 0;
              color: red;
            }
            .noticeWait {
              cursor: pointer;
              font-size: 13px;
            }
          }
        }
      }
      .h_bottom {
        display: flex;
        .warnNotice {
          display: flex;
          justify-content: space-around;
          .warnNoticeBox {
            width: 33.3%;
            text-align: center;
            .warnNoticeNum {
              margin-top: 8px;
              margin-bottom: 0;
              padding-bottom: 10px;
              font-size: 25px;
              color: red;
            }
            .warnNoticeWait {
              font-size: 13px;
              cursor: pointer;
            }
          }
        }
      }
    }
    .h_right {
      width: 39.3%;
      margin-bottom: 10px;
    }
  }
  .notify {
    font-size: 200px;
  }
}
</style>
